import { Application, codo } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";
import { WeWork } from "./type";

/**
 * 第三方应用企业调用， 相关接口集合，全使用suiteCorpAccessToken ，即第三方应用下的企业的accesstoken
 */
export default class SuiteCorp extends WeWorkBaseService {
	constructor(
		protected config: codo.WeWork.IWeWorkConfig,
		private suiteCorpAccessToken: string,
		protected app: Application
	) {
		super(config, app);
	}

	/**
	 * 第三方应用下企业、代开发应用
	 * - 获取应用权限详情
	 * - https://developer.work.weixin.qq.com/document/path/99052
	 */
	async getAppPermissions() {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/agent/get_permissions?access_token=${this.suiteCorpAccessToken}`;

		type Response = { app_permissions: string[] } & WeWork.IResponse;

		const res = await this.curl<Response>(url, {
			method: "post",
			dataType: "json",
			contentType: "json",
			timeout: [30000, 30000],
		});

		if (res.data.errcode && res.data.errcode !== 0) {
			this.app.logger.error(`获取应用权限详情异常 %j`, res.data);
			throw new Error(res.data.errcode + res.data.errmsg);
		}
		return res.data.app_permissions;
	}

	/**
	 * 第三方应用下企业、代开发应用
	 * - 获取管理员列表
	 * - https://developer.work.weixin.qq.com/document/path/100073
	 */
	async getAdminList() {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/agent/get_admin_list?access_token=${this.suiteCorpAccessToken}`;
		type Response = { admin: { userid: string; auth_type: 0 | 1 }[] } & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "post",
			dataType: "json",
			contentType: "json",
			timeout: [30000, 30000],
		});
		if (res.data.errcode && res.data.errcode !== 0) {
			this.app.logger.error(`获取管理员列表异常 %j`, res.data);
			throw new Error(res.data.errcode + res.data.errmsg);
		}
		return res.data.admin;
	}

	/**
	 * 将企业主体下的明文userid转换为服务商主体下的密文userid。
	 * - 使用场景，suite app下，只能拿到密文，而用户企业看到的是明文，需要能匹配。
	 * @param {string[]} userid_list 明文userid列表
	 */
	async userIdToOpenUserId(userid_list: string[]) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/batch/userid_to_openuserid?access_token=${this.suiteCorpAccessToken}`;
		const body = {
			userid_list,
		};
		type Response = {
			open_userid_list: {
				userid: string;
				open_userid: string;
			}[];
			invalid_userid_list: string[];
		} & WeWork.IResponse;

		const res = await this.curl<Response>(url, {
			method: "post",
			dataType: "json",
			contentType: "json",
			data: body,
			timeout: [30000, 30000],
		});

		if (res.data.errcode && res.data.errcode !== 0) {
			this.app.logger.error(
				`将企业主体下的明文userid转换为服务商主体下的密文userid异常 %j`,
				res.data
			);
			throw new Error(res.data.errcode + res.data.errmsg);
		}
		return res.data;
	}
}
